/*
 * Written By	: Chang Hyun Park
 * Student ID	: 2007******
 * Major		: Computer Engineering
 * Subject		: Data Communication
 * Filename		: Receive.java
 */
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

public class Receive extends Thread
{//Thread that received DatagramPacket from server and finds out Server Info
	DatagramSocket clientSocket;
	String buffer;
	byte[] recvData;
	
	
	public Receive(DatagramSocket clientSocket,byte[] recvData)
	{//Constructor with Appropriate Arguments
		this.clientSocket = clientSocket;
		this.recvData = recvData;
	}
	
	/**
	 * @param run Receive which will wait for and receive datagramPacket from the server
	 */
	public void run()
	{
		DatagramPacket recvPacket = new DatagramPacket(recvData, recvData.length);
		try
		{
			clientSocket.receive(recvPacket);	//Receive packet
			InetAddress recvServerIP = recvPacket.getAddress();
			int recvServerPort = recvPacket.getPort();
			buffer = new String(recvPacket.getData());
			System.out.println("Server Echos = \""+buffer+"\"");
			System.out.println("(2)   Server IP and Port number is ["+recvServerIP.toString().substring(1)+":"+recvServerPort+"]\n");
			//Get IP and port from Server's datagram packet
			
		} 

		catch(SocketTimeoutException e)
		{
			System.out.println("Server Timeout!");
			Receive r1;

				try
				{//Try receiving Again...
					r1 = new Receive(clientSocket, recvData);
					r1.start();//Recursively start threads...
					r1.join();//Wait for threads at the same level of recursion tree...
				} catch (InterruptedException e1)
				{
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

		}
		catch (IOException es)
		{
			// TODO Auto-generated catch block
			es.printStackTrace();
		}
	}
}